package commentdao

import (
	"chaoyer/ghost_assist/entity"
	"github.com/sirupsen/logrus"
	"database/sql"
	"chaoyer/ghost_assist/base"
)

// 插入评论
func Insert(comment entity.Comment) (int64, error) {

	stmt, err := base.Db.Preparex(
		"INSERT INTO tb_comment (post_id,parent,creator,content,created_at) values(?,?,?,?,now())")
	if err != nil {
		logrus.Error(err)
		return 0, err
	}
	result, err := stmt.Exec(comment.PostId, comment.Parent, comment.Creator, comment.Content)
	if err != nil {
		logrus.Error(err)
		return 0, err
	}
	lastInsertId, _ := result.LastInsertId()
	return lastInsertId, nil
}

// 根据评论id查找
func FindById(id int) (entity.Comment, error) {

	var v entity.Comment
	// 先查询数据库是否有文章的访问数
	stmt, err := base.Db.Preparex(`SELECT * FROM tb_comment WHERE id = ?`)
	if err != nil {
		logrus.Error(err)
		return v, err
	}
	err = stmt.Get(&v, id)
	if err != nil {
		if err == sql.ErrNoRows {
			logrus.Info(err)
		} else {
			logrus.Error(err)
		}
		return v, err
	}
	return v, nil
}

// 根据评论id查找，时间-parent 排序
func FindByParent(parentId int) ([]entity.Comment, error) {
	var v []entity.Comment
	stmt, err := base.Db.Preparex(`SELECT * FROM tb_comment WHERE parent=? order by created_at desc,parent`)
	if err != nil {
		logrus.Error(err)
		return v, err
	}
	err = stmt.Select(&v, parentId)
	if err != nil {
		if err == sql.ErrNoRows {
			logrus.Info(err)
		} else {
			logrus.Error(err)
		}
		return v, err
	}
	return v, nil
}

func FindByPost(postId string) ([]entity.Comment, error) {

	var v []entity.Comment
	stmt, err := base.Db.Preparex("SELECT * FROM tb_comment WHERE post_id=? and parent=0 order by created_at")
	if err != nil {
		logrus.Error(err)
		return v, err
	}
	err = stmt.Select(&v, postId)
	if err != nil {
		if err == sql.ErrNoRows {
			logrus.Info(err)
		} else {
			logrus.Error(err)
		}
		return v, err
	}
	return v, nil
}
